from flask import request
from core import api, db, logger
import datetime
from flask_jwt_extended import get_jwt_identity

from modules.log import LogModel, LogResource, LogDetail

def log_request(func):
    def wrapper(*args, **kwargs):
        logger.info(f"Request URL: {request.url}")
        logger.info(f"Request Method: {request.method}")
        logger.info(f"Request Headers: {request.headers}")

        account = get_jwt_identity();
        log = LogModel()
        log.account = account
        log.module = func.__module__
        log.action = func.__name__
        log.log_ip = request.remote_addr
        log.params = request.json if (request.method == 'POST' or request.method == 'PUT') else request.args
        log.log_time = datetime.datetime.now()

        result = func(*args, **kwargs)
        logger.info(f"Response Status Code: {result.status_code}")

        log.status = result.status_code
        db.session.add(log)
        db.session.commit()
        return result
    return wrapper
    
api.add_resource(LogResource, '/logs')
api.add_resource(LogDetail, '/logs/<int:id>')


#用户相关
from modules.user import UserResource, UserDetail
api.add_resource(UserResource, '/users')
api.add_resource(UserDetail, '/users/<int:id>')

#模型相关
from modules.models import ModelsResource, ModelsDetail
api.add_resource(ModelsResource, '/models')
api.add_resource(ModelsDetail, '/models/<int:id>')

#训练任务相关
from modules.training import TrainingResource, TrainingDetail
api.add_resource(TrainingResource, '/trainings')
api.add_resource(TrainingDetail, '/trainings/<int:id>')

#数据集相关
from modules.dataset import DatasetResource, DatasetDetail
api.add_resource(DatasetResource, '/datasets')
api.add_resource(DatasetDetail, '/datasets/<int:id>')

#采集任务相关
from modules.collection import CollectionResource, CollectionDetail
api.add_resource(CollectionResource, '/collections')
api.add_resource(CollectionDetail, '/collections/<int:id>')

#摄像机相关
from modules.camera import CameraResource, CameraDetail
api.add_resource(CameraResource, '/cameras')
api.add_resource(CameraDetail, '/cameras/<int:id>')

#图片相关
from modules.image import ImageResource, ImageDetail
api.add_resource(ImageResource, '/images')
api.add_resource(ImageDetail, '/images/<int:id>')


#登录认证相关
import modules.login
import modules.service